package com.sky.service.impl;


import cn.mybatis.mp.core.sql.executor.chain.QueryChain;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Admins;
import com.sky.exception.BaseException;
import com.sky.mapper.AdminsMapper;
import com.sky.properties.JwtProperties;
import com.sky.service.AdminService;
import com.sky.utils.JwtUtil;
import com.sky.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author majun
 * @package com.sky.service.impl
 * @date 2025/6/21 01:35
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminsMapper adminsMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 员工登录
     * @param employeeLoginDTO 员工登录信息
     * @return token 登录成功后返回的token
     */
    public String login(EmployeeLoginDTO employeeLoginDTO) {

        Admins admins = QueryChain.of(adminsMapper)
                .eq(Admins::getUsername, employeeLoginDTO.getUsername())
                .get();

        if (admins == null) {
            throw new BaseException("用户不存在");
        }

        if (!admins.getPassword().equals(Md5Util.getMD5String(employeeLoginDTO.getPassword()))) {
            throw new BaseException("密码错误");
        }

        Map<String, Object> variables = new HashMap<>();
        variables.put(JwtClaimsConstant.USER_ID, admins.getId());

        //生成token
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), variables);

        //将token存进redis
        redisTemplate.opsForValue().set(token, token);
        //设置存储时间
        redisTemplate.expire(token, jwtProperties.getAdminTtl(), TimeUnit.MILLISECONDS);

        return token;
    }
}
